package vip.meeet.jdk.concurent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCondition {

    private final Lock lock = new ReentrantLock();
    private final Condition notFull  = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    private final Task[] tasks = new Task[100];
    private int addIndex;
    private int getIndex;
    private int count;

    public void addTask(Task task) throws InterruptedException {
        lock.lock();
        try {
            // 注意使用的是while，不是if
            while (count == tasks.length) {//如果队列满了
                notFull.await();//notFull条件不满足了，需要等待
            }
            tasks[addIndex++] = task;
            if (addIndex == tasks.length){
                addIndex = 0;
            }
            count++;
            notEmpty.signal();//添加数据之后，非空条件满足了，就可以唤醒等在这个条件上的线程了
        } finally {
            lock.unlock();
        }
    }

    public Task getTask() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {//如果队列为空
                notEmpty.await();//队列为空，非空条件不满足了，需要等待
            }
            Task task = tasks[getIndex++];
            if (getIndex == tasks.length) {
                getIndex = 0;
            }
            count--;
            notFull.signal();//数据被取出之后，notFull条件满足了，需要唤醒等待notFull条件的线程
            return task;
        } finally {
            lock.unlock();
        }
    }

    private static class Task{

    }
}
